from pydantic import BaseModel
from .common import *
from typing import List, Optional
from enum import Enum

class LOGIN_TYPE(Enum):
    password = 0,
    phone = 1,
    weixin = 11

class UserInfo(TSModel):
    __table__ = 'tb_user_info'
    group_id: int = PrimaryKey(index=0)
    uid: int = PrimaryKey(index=1, autoincrement=True)
    
    nickname: str = Column(default='')
    sex: int = Column(default=0)
    age: int = Column(default=0)

    created_ms: Optional[int] = Column(default_factory=default_created_ms)
    updated_ms: int = Column(default_factory=default_updated_ms)


class UserRelation(TSModel, model=True):
    # group_id: str = PrimaryKey(index=0)
    uid_addtion: str = PrimaryKey(index=1)

    @property
    def uid(self) -> int:
        if not self.uid_addtion:
            return 0
        return int(self.uid_addtion.split('_')[1])
    
    @property
    def uid_group_id(self) -> int:
        if not self.uid_addtion:
            return 0
        return int(self.uid_addtion.split('_')[0])
    

class UserOauth(UserRelation):
    __table__ = 'tb_user_oauth'
    groud_id: int = PrimaryKey(index=0)
    id: int = PrimaryKey(index=2, autoincrement=True)
    type: LOGIN_TYPE = PrimaryKey(index=2)

    open_id: Optional[str] = Column()
    password: Optional[str] = Column()
    token: Optional[str]= Column()

    created_ms: Optional[int] = Column(default_factory=default_created_ms)
    updated_ms: int = Column(default_factory=default_updated_ms)

class User(BaseModel):
    user_info: UserInfo
    user_oauth: List[UserOauth] = []

    def get_oauth(self, type: LOGIN_TYPE) -> Optional[UserOauth]:
        for oauth in self.user_oauth:
            if oauth.type == type:
                return oauth
        return None

class Token(BaseModel):
    access_token: str
    token_type: str = "bearer"




